package com.heyxampis.newmantis.controller.generico.service;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.heyxampis.newmantis.controller.generico.dao.DAOAbstrato;
import com.heyxampis.newmantis.model.Entidade;

@Service
public class ServiceAbstratoImpl<T extends Entidade, ID extends Serializable> implements ServiceAbstrato<T, ID>, Serializable  {

	private static final long serialVersionUID = -5766148753992130155L;

	private static final Log LOG = LogFactory.getLog(ServiceAbstratoImpl.class);
	
	private DAOAbstrato<T, ID> dao;
	
	@Override
	@Transactional(readOnly = true)
	public T findPorId(ID id) {
		T t = null;
		try{
			t = (T) dao.findPorId(id);
		}catch(Exception e){
			LOG.error(e.getMessage(), e);
		}
		return t;
	}

	@Override
	@Transactional(readOnly = true)
	public List<T> listar() {
		List<T> lista = null;
		try{
			lista = (List<T>) dao.listar();
		}catch(Exception e){
			LOG.error(e.getMessage(), e);
		}
		return lista;
	}

	@Override
	@Transactional
	public Long save(T entity) {
		Long idRetorno = null;
		try{
			idRetorno = dao.save(entity);
		}catch(Exception e){
			LOG.error(e.getMessage(), e);
		}
		return idRetorno;
	}

	@Override
	@Transactional
	public boolean merge(T entity) {
		boolean retorno = false;
		try{
			retorno = dao.merge(entity);
		}catch(Exception e){
			LOG.error(e.getMessage(), e);
		}
		return retorno;
	}

	@Override
	@Transactional
	public boolean update(T entity) {
		boolean retorno = false;
		try{
			retorno = dao.update(entity);
		}catch(Exception e){
			LOG.error(e.getMessage(), e);
		}
		return retorno;
	}

	@Override
	@Transactional
	public boolean saveOrUpdate(T entity) {
		boolean retorno = false;
		try{
			retorno = dao.saveOrUpdate(entity);
		}catch(Exception e){
			LOG.error(e.getMessage(), e);
		}
		return retorno;
	}

	@Override
	@Transactional
	public boolean delete(T entity) {
		boolean retorno = false;
		try{
			retorno = dao.delete(entity);
		}catch(Exception e){
			LOG.error(e.getMessage(), e);
		}
		return retorno;
	}

	@Override
	@Transactional(readOnly = true)
	public Criteria criarCriteria(T entity) {
		Criteria criteria = null;
		try{
			criteria = dao.criarCriteria(entity);
		}catch(Exception e){
			LOG.error(e.getMessage(), e);
		}
		return criteria;
	}

}
